package com.jpa.repository.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.hibernate.SQLQuery;
import org.hibernate.transform.Transformers;

import com.jpa.domain.User;
import com.jpa.repository.custom.UserRepositoryCustom;

/**
 * @Description UserRepository 扩展接口实现类
 *
 * @author 堆堆堆
 * @date 2018年4月19日 下午6:33:03
 */
@SuppressWarnings({ "deprecation", "unchecked" })
public class UserRepositoryImpl implements UserRepositoryCustom {

	@PersistenceContext
	private EntityManager entityManager;

	@Override
	public List<User> findByScore(Double score) {

		// 定义查询 sql
		StringBuilder sql = new StringBuilder();
		sql.append("select * from t_user ");

		// 动态拼接 sql
		if (score != null)
			sql.append("where score = :score");
		
		// 定义返回 map 类型，怎么又弃用了卧槽？？？...
		// Query query = entityManager.createNativeQuery(sql.toString());
		// query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);

		// 定义返回实体类型
		Query query = entityManager.createNativeQuery(sql.toString(), User.class);

		// 传入参数
		if (score != null)
			query.setParameter("score", 99.5D);

		return query.getResultList();
	}

}
